﻿using System;
using System.Web.Caching;
using Microsoft.Practices.ServiceLocation;
using Pap.Core.CronJobs;
using Pap.Core.Utilities;
using Pap.Data;
using Pap.Data.Abstraction.Utils;
using Pap.Services;
using Pap.Services.WorkflowEngine;

namespace Pap.Web.Utils.CronJobs
{
    /// <summary>
    /// 
    /// </summary>
    public class DeleteNewBoardStuckLoansCronJob : ICronJob
    {
        /// <summary>
        /// 
        /// </summary>
        IWorkflowService _WorkflowService;
        /// <summary>
        /// 
        /// </summary>
        IAdministrationRepository _AdministrationRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="DeleteNewBoardStuckLoansCronJob"/> class.
        /// </summary>
        /// <param name="workflowService">The workflow service.</param>
        /// <param name="adminRepository">The admin repository.</param>
        public DeleteNewBoardStuckLoansCronJob(IWorkflowService workflowService, IAdministrationRepository adminRepository)
        {
            _WorkflowService = workflowService;
            _AdministrationRepository = adminRepository;
        }

        #region ICronJob Members

        /// <summary>
        /// Gets the sliding time.
        /// </summary>
        public TimeSpan SlidingTime
        {
            get { return TimeSpan.FromDays(1); }
        }

        /// <summary>
        /// Gets the name of the job.
        /// </summary>
        /// <value>
        /// The name of the job.
        /// </value>
        public string JobName
        {
            get { return "Delete StuckedLoans"; }
        }

        /// <summary>
        /// Executes this instance.
        /// </summary>
        public void Execute()
        {
            using (IUnitOfWork trans = ServiceLocator.Current.GetInstance<IUnitOfWork>())
            {
                string settingValue = _AdministrationRepository.GetSettingValue(RegistryInfo.CommitteeID, SettingKeys.PeriodBeforeEndStuckLoan);
                if (!settingValue.IsNullOrEmpty())
                {
                    int monthsPeriod = settingValue.ToInt32();
                    var newBoardLoansSteps = _WorkflowService.GetInstancesInStep(Steps.BoardWaitingList);

                    newBoardLoansSteps.ForEach(step =>
                        {
                            if (step.CreationDate.Date < DateTime.Today.Date.AddMonths(-monthsPeriod))
                                _WorkflowService.Move(ActionTypes.Close, step.ProcessInstanceID, step.UserID,
                                    step.Comments, null);
                        }
                    );
                    trans.Commit();
                }
            }

        }

        #endregion
    }
}
